// 导入表单验证插件
import wxValidate from 'wechat-validate'
const app = getApp()

Page({
  data: {
    countDownVisible: false,
    mobile: '17613273956',
    code: '',
    redirectURL: ''
  },
  // 将插件注入到页面实例中
  behaviors: [wxValidate],
  onLoad (options) {
    console.log(options.redirectURL)
    this.setData({ redirectURL: options.redirectURL })
  },
  rules: {
    mobile: [
      { required: true, message: '请填写手机号码!' },
      { pattern: /^1[3-8]\d{9}$/, message: '请填写正确的手机号码!' }
    ],
    code: [
      { required: true, message: '请填写验证码!' },
      { pattern: /^\d{6}$/, message: '请填写正确的验证码!' }
    ]
  },

  async showCountDown () {
    //校验
    const { message, valid } = this.validate('mobile')
    if (!valid) return wx.utils.toast(message)
    // 显示倒计时组件
    this.setData({ countDownVisible: true })
    //获取验证码
    const { code, data } = await wx.http.get('/code', { mobile: this.data.mobile })
    // 检测验证码是否发送成功
    console.log(data.code) //验证码
    if (code !== 10000) return wx.utils.toast('发送失败，稍后重试!')
  },
  //登录
  async loginOrRegister () {
    const { message, valid } = this.validate('code')
    if (!valid) return wx.utils.toast(message)
    const {
      code,
      message: remessage,
      data
    } = await wx.http.post('/login', {
      mobile: this.data.mobile,
      code: this.data.code
    })
    if (code !== 10000) return wx.utils.toast(remessage)
    //记录登录状态
    app.setToken('token', data.token)
    app.setToken('refreshToken', data.refreshToken)
    // 重定向
    wx.redirectTo({
      url: '/' + this.data.redirectURL
    })
  },

  countDownChange (ev) {
    this.setData({
      timeData: ev.detail,
      countDownVisible: ev.detail.minutes === 1 || ev.detail.seconds > 0
    })
  }
})
